package com.dhms.vostok1.ui.main.mine

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.dhms.vostok1.BuildConfig
import com.dhms.basebusiness.R
import com.dhms.vostok1.adapter.BaseListAdapter
import com.dhms.vostok1.data.BaseListItem
import com.dhms.vostok1.data.OnBaseListItemClickListener
import com.dhms.vostok1.databinding.FragmentAboutBinding
import com.dhms.vostok1.model.SettingViewModel
import com.dhms.vostok1.model.UserViewModel
import com.dhms.vostok1.ui.main.MainActivity
import com.permissionx.guolindev.PermissionX

class AboutFragment : Fragment() {
    private var _binding: FragmentAboutBinding? = null
    private val binding get() = _binding!!

    private val userViewModel: UserViewModel by activityViewModels()
    private val settingViewModel: SettingViewModel by activityViewModels()

    private var isDevMode = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentAboutBinding.inflate(inflater, container, false)

        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.viewModel = userViewModel
        binding.lifecycleOwner = viewLifecycleOwner
        setToolBar()
        setOptionList()
        setOnBrandClickListener()
    }

    private fun setToolBar() {
        binding.topAppBar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun setOptionList() {
        val onBaseListItemClickListener: OnBaseListItemClickListener = {
            when (it) {
                0 -> {
                }
                1 -> {
                    PermissionX.init(this)
                        .permissions(Manifest.permission.CALL_PHONE)
                        .request { allGranted, _, _ ->
                            if (allGranted) {
                                val intent = Intent(Intent.ACTION_DIAL).apply {
                                    data =
                                        Uri.parse("tel:" + getString(R.string.about_option_contact_number))
                                }
                                startActivity(intent)
                            } else {
                                Toast.makeText(requireContext(), "请先授予电话权限！", Toast.LENGTH_SHORT)
                                    .show()
                            }
                        }
                }
                2 -> {
                    if (activity is MainActivity) {
                        findNavController().navigate(R.id.action_aboutFragment_to_settingFragment)
                    } else {
                        findNavController().navigate(R.id.action_aboutFragmentInLogin_to_settingFragmentInLogin)
                    }
                }
            }
        }
        val optionList = mutableListOf(
            BaseListItem(
                itemTitle = getString(R.string.about_option_version),
                itemValue = getString(R.string.app_version, BuildConfig.VERSION_NAME, BuildConfig.CI_COMMIT_SHORT_SHA)
            ),
            BaseListItem(
                itemTitle = getString(R.string.about_option_contact),
                itemValue = getString(R.string.about_option_contact_number),
                itemSuffixIcon = ResourcesCompat.getDrawable(
                    resources,
                    com.dhms.vostok1.R.drawable.ic_arrow_right,
                    null
                )
            ),
        )
        if (settingViewModel.settingMap.value!!["DEV_MODE"] as Boolean) {
            optionList.add(
                BaseListItem(
                    itemTitle = getString(R.string.setting),
                    itemSuffixIcon = ResourcesCompat.getDrawable(
                        resources,
                        com.dhms.vostok1.R.drawable.ic_arrow_right,
                        null
                    )
                )
            )
        }
        binding.aboutOptionList.adapter = BaseListAdapter(
            requireContext(), optionList, onBaseListItemClickListener
        )
    }

    private fun setOnBrandClickListener() {
        val clickCount = 5
        var clickHits = LongArray(clickCount)
        val clickDuration = 2000

        binding.aboutAppIcon.setOnClickListener {
            System.arraycopy(clickHits, 1, clickHits, 0, clickHits.size - 1)
            clickHits[clickHits.size - 1] = SystemClock.uptimeMillis()
            if (clickHits[0] >= (SystemClock.uptimeMillis() - clickDuration)) {
                val isDevMode = settingViewModel.settingMap.value!!["DEV_MODE"] as Boolean
                settingViewModel.writeSettings(
                    mapOf(
                        "DEV_MODE" to !isDevMode
                    )
                )
                this.isDevMode = isDevMode
                Toast.makeText(
                    requireContext(),
                    "您已${if (isDevMode) "退出" else "进入"}开发者模式！",
                    Toast.LENGTH_SHORT
                ).show()
                clickHits = LongArray(clickCount)

                setOptionList()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (isDevMode != settingViewModel.settingMap.value!!["DEV_MODE"] as Boolean) {
            setOptionList()
        }
    }
}